package com.example._05mvcboot03.common.exception;

import com.example._05mvcboot03.common.response.JsonResult;
import com.example._05mvcboot03.common.response.StatesCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleBindException(BindException be)
    {
        String message=be.getFieldError().getDefaultMessage();
        log.error(".BindException:"+message);
        return new JsonResult(StatesCode.VALIDATED_ERROR,message);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException csen){
        String message=csen.getMessage().split(":")[1].trim();
        log.error(".ConstraintViolationException:"+message);
        return new JsonResult(StatesCode.VALIDATED_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable t){
        String message=t.getMessage();
        log.error("Throwable:"+message);
        return new JsonResult(StatesCode.VALIDATED_ERROR,message);
    }
}
